<?php
/**
 * Nordic Repository
 * 
 * LICENSE
 * 
 * The new BSD license is applied on this source-file. For further
 * information please visit http://license.nordic-dev.de/newbsd.txt
 * or send an email to andre.moelle@gmail.com.
 */

/**
 * Necessary includes.
 */
Zend_Loader::loadClass('Zend_Db_Table_Abstract');
Zend_Loader::loadClass('Nordic_Auth_Record_User');

/**
 * Represents the table "auth_user".
 * 
 * @category   Nordic
 * @package    Nordic_Auth
 * @copyright  2007 Nordic Development
 * @license    http://license.nordic-dev.de/newbsd.txt (New-BSD license)
 * @author     Andre Moelle <andre.moelle@gmail.com>
 * @version    $Id: User.php 3 2007-07-08 09:21:42Z andre.moelle $
 */
class Nordic_Auth_Model_User extends Zend_Db_Table_Abstract
{
	/**
	 * @see Zend_Db_Table::_name
	 */
	protected $_name = 'auth_user';
	
	/**
	 * @see Zend_Db_Table_Abstract::$_rowClass
	 */
	protected $_rowClass = 'Nordic_Auth_Record_User';
	
	/**
	 * Returns an user with the given username.
	 * 
	 * @param string $username
	 * @return Nordic_Auth_Record_User
	 */
	public function findByUsername ($username)
	{
		$select = $this->_db->select();
		$select->from($this->_name);
		$select->where('username = ?', $username);
		$select->limit(1);
		
		$array = $select->query()->fetch();
		
		if(!$array)
		{
			return false;
		}
		
		$result = $this->fetchNew();
		$result->setFromArray($array);
		
		return $result;
	}
	
	/**
	 * 
	 */
	public function findUniques ($username, $email)
	{
		$select = $this->_db->select();
		$select->from($this->_name, array('id', 'username', 'email'));
		$select->where('username = ?', $username);
		$select->orWhere('email = ?', $email);
		$select->limit(2);
		
		return $select->query()->fetchAll();
	}
	
	/**
	 * Returns the object of an user.
	 * 
	 * @param integer $id id of the user
	 * @return Nordic_Auth_Record_User
	 */
	public function getUser ($id)
	{
		return parent::fetchRow($this->_db->quoteInto('id = ?', $id));
	}
	
	/**
	 * Returns the username of the given id.
	 * 
	 * @param integer $id user-id
	 * @return string|false
	 */
	public function getUsername ($id)
	{
		$row = $this->getUser($id);
		
		if($row == null)
		{
			return false;
		}
		
		return $row->username;
	}
	
	/**
	 * Updates the login-time of a given id.
	 * 
	 * @param integer $id id of the user who logged in
	 * @return integer
	 */
	public function updateLogin ($id)
	{
		return $this->_db->query(
			'UPDATE ' . $this->_name . ' ' .
			'SET login_time = ? ' .
			'WHERE id = ? ' .
			'LIMIT 1',
			array(
				date('Y-m-d H:i:s'),
				$id
			)
		)
		->rowCount();	
	}
	
	/**
	 * Updates the time of the last try.
	 * 
	 * @param integer $id id of the user whose account was attempted to login
	 * @return integer
	 */
	public function updateTry ($id)
	{
		return $this->_db->query(
			'UPDATE ' . $this->_name . ' ' .
			'SET lasttry = ? ' .
			'WHERE id = ? ' .
			'LIMIT 1',
			array(
				date('Y-m-d H:i:s'),
				$id
			)
		)
		->rowCount();
	}
}
?>